<template>
    <div class="survey-info-page">
        <!-- 页面标题 -->
        <div class="page-header">
            <h1>查勘信息记录</h1>
            <p>展示已完成的查勘记录信息</p>
        </div>

        <!-- 搜索筛选区域 -->
        <div class="search-container">
            <el-row :gutter="24" class="mb-4">
                <!-- 报案号搜索 -->
                <el-col :span="6">
                    <el-input v-model="searchForm.reportNo" placeholder="请输入报案号" prefix-icon="Search" clearable
                        @keyup.enter="handleSearch" />
                </el-col>
                <!-- 查勘员工号搜索 -->
                <el-col :span="6">
                    <el-input v-model="searchForm.surveyInWorkNo" placeholder="请输入查勘员工号" prefix-icon="User" clearable
                        @keyup.enter="handleSearch" />
                </el-col>
                <!-- 搜索/重置按钮 -->
                <el-col :span="6" class="btn-group">
                    <el-button type="primary" icon="Search" @click="handleSearch">搜索</el-button>
                    <el-button type="default" icon="RefreshLeft" @click="resetSearch" class="ml-2">重置</el-button>
                </el-col>
            </el-row>
        </div>

        <!-- 查勘记录列表表格 -->
        <el-table :data="surveyList" border stripe :loading="tableLoading" style="width: 100%"
            :header-cell-style="{ background: '#f8f9fa', fontWeight: '500' }" empty-text="暂无查勘记录"
            :row-key="row => row.surveyId">
            <!-- 序号 -->
            <el-table-column label="序号" type="index" align="center" min-width="60">
                <template #default="scope">
                    {{ (currentPage - 1) * pageSize + scope.$index + 1 }}
                </template>
            </el-table-column>
            <!-- 报案号 -->
            <el-table-column prop="reportNo" label="报案号" align="center" min-width="200" />

            <!-- 查勘员工号（本司） -->
            <el-table-column prop="surveyInWorkNo" label="查勘员工号" align="center" min-width="140">
                <template #default="scope">
                    <span>{{ scope.row.surveyInWorkNo || '--' }}</span>
                </template>
            </el-table-column>

            <!-- 损失类型 -->
            <el-table-column prop="lossType" label="损失类型" align="center" min-width="100">
                <template #default="scope">
                    <el-tag :type="getLossTypeTagType(scope.row.lossType)" size="small">
                        {{ getLossTypeText(scope.row.lossType) }}
                    </el-tag>
                </template>
            </el-table-column>

            <!-- 受灾面积 -->
            <el-table-column prop="disasterArea" label="受灾面积" align="center" min-width="120">
                <template #default="scope">
                    <span>{{ scope.row.disasterArea ? scope.row.disasterArea + '亩' : '--' }}</span>
                </template>
            </el-table-column>

            <!-- 损失数量 -->
            <el-table-column prop="disasterMount" label="损失数量" align="center" min-width="120">
                <template #default="scope">
                    <span>{{ scope.row.disasterMount || '--' }}</span>
                </template>
            </el-table-column>

            <!-- 预估损失金额 -->
            <el-table-column prop="surveyMoney" label="预估损失金额" align="center" min-width="140">
                <template #default="scope">
                    <span>{{ scope.row.surveyMoney ? '¥' + scope.row.surveyMoney : '--' }}</span>
                </template>
            </el-table-column>

            <!-- 查勘状态 -->
            <el-table-column prop="surveyStatus" label="查勘状态" align="center" min-width="100">
                <template #default="scope">
                    <el-tag :type="getSurveyStatusTagType(scope.row.surveyStatus)" size="small">
                        {{ getSurveyStatusText(scope.row.surveyStatus) }}
                    </el-tag>
                </template>
            </el-table-column>

            <!-- 查勘开始时间 -->
            <el-table-column prop="surverStartTime" label="查勘开始时间" align="center" min-width="250">
                <template #default="scope">
                    {{ formatDateTime(scope.row.surverStartTime) || '--' }}
                </template>
            </el-table-column>

            <!-- 查勘结束时间 -->
            <el-table-column prop="surverEndTime" label="查勘结束时间" align="center" min-width="250">
                <template #default="scope">
                    {{ formatDateTime(scope.row.surverEndTime) || '--' }}
                </template>
            </el-table-column>

            <!-- 操作列 -->
            <el-table-column label="操作" align="center" min-width="120" fixed="right">
                <template #default="scope">
                    <el-button type="primary" @click="openDetailDialog(scope.row)">
                        详情
                    </el-button>
                </template>
            </el-table-column>
        </el-table>

        <!-- 分页控件 -->
        <div class="pagination-container" v-if="total > 0 && !tableLoading">
            <el-pagination @size-change="handlePageSizeChange" @current-change="handleCurrentPageChange"
                :current-page="currentPage" :page-sizes="[5, 10, 20, 50]" :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper" :total="total" background />
        </div>

        <!-- 空数据/加载失败提示 -->
        <div class="empty-container" v-else-if="!tableLoading">
            <el-empty :description="errorMsg || '暂无查勘记录，请调整搜索条件后重试'" image-size="100" />
            <el-button type="text" class="mt-4" @click="fetchData" v-if="errorMsg">
                重新加载
            </el-button>
        </div>

        <!-- 详情弹窗 -->
        <el-dialog title="查勘记录详情" v-model="detailDialogVisible" width="70%" destroy-on-close>
            <el-form :model="currentDetailData" label-width="150px" class="detail-form" size="medium">
                <el-row :gutter="20">
                    <!-- 基础信息 -->
                    <el-col :span="12">
                        <el-form-item label="报案号">
                            <el-input :value="currentDetailData.reportNo" disabled />
                        </el-form-item>
                    </el-col>

                    <!-- 查勘人员信息 -->
                    <el-col :span="12">
                        <el-form-item label="查勘员工号">
                            <el-input :value="currentDetailData.surveyInWorkNo || '--'" disabled />
                        </el-form-item>
                    </el-col>

                    <!-- 损失信息 -->
                    <el-col :span="12">
                        <el-form-item label="损失类型">
                            <el-tag :type="getLossTypeTagType(currentDetailData.lossType)" size="small">
                                {{ getLossTypeText(currentDetailData.lossType) }}
                            </el-tag>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="受灾面积">
                            <el-input
                                :value="currentDetailData.disasterArea ? currentDetailData.disasterArea + '亩' : '--'"
                                disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="损失数量">
                            <el-input :value="currentDetailData.disasterMount || '--'" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="预估损失金额">
                            <el-input
                                :value="currentDetailData.surveyMoney ? '¥' + currentDetailData.surveyMoney : '--'"
                                disabled />
                        </el-form-item>
                    </el-col>

                    <!-- 查勘信息 -->
                    <el-col :span="24">
                        <el-form-item label="受灾原因">
                            <el-input :value="currentDetailData.disasterReason || '--'" disabled rows="2"
                                type="textarea" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="查勘地点">
                            <el-input :value="currentDetailData.surveyAddress || '--'" disabled rows="2"
                                type="textarea" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="查勘现场照片">
                            <div v-if="currentSurveyPhotos.length > 0" class="photo-container">
                                <div class="photo-grid">
                                    <el-image v-for="(photo, index) in currentSurveyPhotos" :key="`photo-${index}`"
                                        :src="photo" :preview-src-list="currentSurveyPhotos" :initial-index="index"
                                        fit="cover" class="photo-item" :lazy="true" :preview-teleported="true"
                                        :hide-on-click-modal="false"
                                        :style="{ width: '200px', height: '150px', borderRadius: '8px', marginRight: '10px', marginBottom: '10px' }" />
                                </div>
                            </div>
                            <span v-else>--</span>
                        </el-form-item>
                    </el-col>

                    <!-- 时间信息 -->
                    <el-col :span="12">
                        <el-form-item label="查勘开始时间">
                            <el-input :value="formatDateTime(currentDetailData.surverStartTime) || '--'" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="查勘结束时间">
                            <el-input :value="formatDateTime(currentDetailData.surverEndTime) || '--'" disabled />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="查勘状态">
                            <el-tag :type="getSurveyStatusTagType(currentDetailData.surveyStatus)" size="small">
                                {{ getSurveyStatusText(currentDetailData.surveyStatus) }}
                            </el-tag>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="detailDialogVisible = false">关闭</el-button>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import hxxp from '@/utils/hxxp.js'

// 状态管理
const tableLoading = ref(false)
const surveyList = ref([])
const total = ref(0)
const totalPages = ref(0)
const errorMsg = ref('')

// 分页参数
const currentPage = ref(1)
const pageSize = ref(10)

// 搜索表单
const searchForm = ref({
    reportNo: '',
    surveyInWorkNo: '',
    lossType: ''
})

// 详情弹窗相关变量
const detailDialogVisible = ref(false)
const currentDetailData = ref({})

// 计算属性：当前详情数据的图片列表
const currentSurveyPhotos = computed(() => {
    return getSurveyPhotos(currentDetailData.value.surveyPhoto)
})

// 打开详情弹窗
const openDetailDialog = (row) => {
    currentDetailData.value = { ...row }
    detailDialogVisible.value = true
}

/**
 * 获取查勘记录数据
 */
const fetchData = async () => {
    try {
        tableLoading.value = true
        errorMsg.value = ''

        // 构造请求参数
        const queryParams = {
            pageNum: currentPage.value,
            pageSize: pageSize.value,
            // 仅当搜索条件有值时传递
            ...(searchForm.value.reportNo && { reportNo: searchForm.value.reportNo.trim() }),
            ...(searchForm.value.surveyInWorkNo && { surveyInWorkNo: searchForm.value.surveyInWorkNo.trim() }),
            ...(searchForm.value.lossType && { lossType: searchForm.value.lossType })
        }

        // 调用接口获取查勘记录数据
        const res = await hxxp.get('/aiSurveyReport/selectDispatch', {
            params: queryParams,
            timeout: 10000
        })

        console.log('后端响应数据:', res)
        const response = res || {}

        // 校验后端返回格式
        if (response.code !== 100200) {
            throw new Error(`接口错误: ${response.msg || '未知错误'}`)
        }

        // 提取分页和列表数据
        const data = response.data || {}
        surveyList.value = Array.isArray(data.list) ? data.list : []
        total.value = Number(data.total) || 0
        totalPages.value = Number(data.totalPages) || 0
        currentPage.value = Number(data.pageNum) || 1

    } catch (error) {
        console.error('请求失败:', error)
        surveyList.value = []
        total.value = 0
        totalPages.value = 0

        // 错误分类提示
        if (error.response) {
            errorMsg.value = `请求失败（${error.response.status}）: ${error.response.statusText || '服务器异常'}`
        } else {
            errorMsg.value = error.message || '数据加载失败，请检查网络'
        }

        ElMessage.error(errorMsg.value)
    } finally {
        tableLoading.value = false
    }
}

// 分页变更处理
const handleCurrentPageChange = (page) => {
    currentPage.value = page
    fetchData()
}

const handlePageSizeChange = (size) => {
    pageSize.value = size
    currentPage.value = 1
    fetchData()
}

// 搜索与重置
const handleSearch = () => {
    currentPage.value = 1
    fetchData()
}

const resetSearch = () => {
    searchForm.value = {
        reportNo: '',
        surveyInWorkNo: '',
        lossType: ''
    }
    currentPage.value = 1
    fetchData()
}

// 页面初始化加载数据
onMounted(() => {
    fetchData()
})

/**
 * 损失类型文本转换
 */
const getLossTypeText = (type) => {
    const typeMap = {
        1: '作物',
        2: '牲畜',
        3: '农机',
        4: '其他',
        null: '--'
    }
    return typeMap[type] || '未知类型'
}

/**
 * 损失类型标签样式
 */
const getLossTypeTagType = (type) => {
    switch (type) {
        case 1: return 'success' // 作物-成功色
        case 2: return 'warning' // 牲畜-警告色
        case 3: return 'info'    // 农机-信息色
        case 4: return 'default' // 其他-默认色
        default: return 'default'
    }
}

/**
 * 查勘状态文本转换
 */
const getSurveyStatusText = (status) => {
    const statusMap = {
        1: '待查勘',
        2: '查勘中',
        3: '已查勘',
        null: '--'
    }
    return statusMap[status] || '未知状态'
}

/**
 * 查勘状态标签样式
 */
const getSurveyStatusTagType = (status) => {
    switch (status) {
        case 1: return 'warning' // 待查勘-警告色
        case 2: return 'info'    // 查勘中-信息色
        case 3: return 'success' // 已查勘-成功色
        default: return 'default'
    }
}

/**
 * 时间格式化
 */
const formatDateTime = (dateStr) => {
    if (!dateStr) return ''
    const date = new Date(dateStr)
    if (isNaN(date.getTime())) return dateStr

    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')
        }-${String(date.getDate()).padStart(2, '0')
        } ${String(date.getHours()).padStart(2, '0')
        }:${String(date.getMinutes()).padStart(2, '0')
        }:${String(date.getSeconds()).padStart(2, '0')
        }`
}

/**
 * 处理查勘现场照片，支持多张图片
 */
const getSurveyPhotos = (photoStr) => {
    if (!photoStr) return []

    // 按逗号分割图片URL
    const photos = photoStr.split(',').map(url => url.trim()).filter(url => url)
    return photos
}
</script>

<style scoped>
.survey-info-page {
    padding: 20px;
    background-color: #ffffff;
    min-height: calc(100vh - 60px);
    box-sizing: border-box;
}

.page-header {
    margin-bottom: 24px;
    padding-bottom: 12px;
    border-bottom: 1px solid #eeeeee;
}

.page-header h1 {
    font-size: 20px;
    font-weight: 600;
    color: #333333;
    margin: 0 0 8px;
}

.page-header p {
    font-size: 14px;
    color: #666666;
    margin: 0;
    line-height: 1.5;
}

.search-container {
    margin-bottom: 20px;
}

.btn-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.el-table {
    margin-bottom: 16px;
}

.el-table td,
.el-table th {
    font-size: 13px;
    color: #333333;
    line-height: 1.8;
}

.el-table th {
    background-color: #f8f9fa !important;
}

.pagination-container {
    margin-top: 8px;
    display: flex;
    justify-content: flex-end;
    padding-right: 4px;
}

.empty-container {
    margin: 60px auto;
    text-align: center;
    width: 100%;
}

.empty-container .el-button--text {
    margin-top: 16px;
    color: #409eff;
}

.photo-container {
    display: flex;
    align-items: flex-start;
}

.photo-grid {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
}

.photo-item {
    cursor: pointer;
    transition: all 0.3s ease;
    border: 2px solid #e4e7ed;
    object-fit: cover;
    background-color: #f5f7fa;
}

.photo-item:hover {
    transform: scale(1.02);
    border-color: #409eff;
    box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

/* 优化图片预览样式 */
:deep(.el-image__preview) {
    background-color: rgba(0, 0, 0, 0.8);
}

:deep(.el-image-viewer__wrapper) {
    z-index: 9999;
}

:deep(.el-image-viewer__canvas) {
    transition: none;
}

.detail-form .el-form-item {
    margin-bottom: 16px;
}

.detail-form .el-form-item__label {
    font-size: 13px;
    font-weight: 500;
}

/* 响应式适配 */
@media (max-width: 1200px) {
    .search-container .el-col {
        flex: 1 1 auto;
        max-width: 100%;
    }

    .el-table {
        overflow-x: auto;
        width: 100%;
    }
}

@media (max-width: 768px) {
    .survey-info-page {
        padding: 12px 8px;
    }

    .pagination-container {
        justify-content: center;
        padding-right: 0;
    }
}
</style>
